﻿using System;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using System.IO;

namespace CodeArt.SharePoint.Configuration
{

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;

    /// <summary>
    /// SharePointSettings
    /// </summary>
    public sealed class SharePointSettings
    {
        private string _configurationFilepath = SPUtility.GetGenericSetupPath("Config") + @"\codeArtSharePoint.config";

        private ExeConfigurationFileMap fileMap;
        private System.Configuration.Configuration cachedConfiguration;
        private object cachedConfigurationLock = new object();

        public SharePointSettings()
            : this(string.Empty,true)
        {

        }

        public SharePointSettings(string configurationFilepath)
            : this(configurationFilepath, true)
        {

        }

        internal SharePointSettings(string configurationFilepath, bool refresh)
        {
            if( !string.IsNullOrEmpty(configurationFilepath))
                this._configurationFilepath = configurationFilepath;
            
            this.fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = _configurationFilepath;
        }

        private System.Configuration.Configuration GetConfiguration()
        {
            if (cachedConfiguration == null)
            {
                lock (cachedConfigurationLock)
                {
                    if (cachedConfiguration == null)
                    {
                        cachedConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    }
                }
            }

            return cachedConfiguration;
        }

        public ConfigurationSection GetSection(string sectionName)
        {
            System.Configuration.Configuration configuration = GetConfiguration();

            ConfigurationSection configurationSection = configuration.GetSection(sectionName) as ConfigurationSection;

            return configurationSection;
        }

        internal void UpdateCache()
        {
            System.Configuration.Configuration newConfiguration
                = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            lock (cachedConfigurationLock)
            {
                cachedConfiguration = newConfiguration;
            }
        }
    }
}
